﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Questionary.Logic
{
	/// <summary>
	/// 序列化对象
	/// </summary>
	public class FileHelper
	{
		public static T GetObject<T>(string filePath)
		{
			try
			{
				if (!File.Exists(filePath))
				{
					return default(T);
				}

				string content = File.ReadAllText(filePath);


				using (StringReader rdr = new StringReader(content))
				{
					XmlSerializer serializer = new XmlSerializer(typeof(T));
					//反序列化，并将反序列化结果值赋给变量i
					return (T)serializer.Deserialize(rdr);
				}
			}
			catch (Exception ex)
			{
				return default(T);
			}
		}


		public static bool WriteObject<T>(T obj, string filePath)
		{
			try
			{
				XmlSerializer serializer = new XmlSerializer(typeof(T));

				if (File.Exists(filePath))
				{
					File.WriteAllText(filePath,"");
				}

				using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
				{
					//执行序列化并将序列化结果输出到控制台
					serializer.Serialize(fs, obj);
				}

				return true;
			}
			catch (Exception ex)
			{
				return false;
			}

		}

	}

	public class FilePaths
	{
		public static string QuestionFilePath = "/QCF/questions.xml";
		public static string ActivityFolder = "/QCF/Activity/";
		public static string GeneralExcelFilePath = "/QCF/General.xls";
	}
}